<?php

namespace app\common\model;


use app\common\lib\Status;

class MallCate extends TimeModel
{

    protected $name = "mall_cate";

    protected $deleteTime = "delete_time";

    public function getPidCateListInfo()
    {
        $list = $this->field('id,pid,title,id as type,title as name')
            ->where([
                ['status', '=', 1],
            ])
            ->select()
            ->toArray();
        return $this->buildPidMenu(0, $list);
    }

    /**
     * @param $pid
     * @param $list
     * @param $level
     * @return array
     */
    protected function buildPidMenu($pid, $list, $level = 0): array
    {
        $newList = [];
        foreach ($list as $vo) {
            if ($vo['pid'] == $pid) {
                $level++;
                foreach ($newList as $v) {
                    if ($vo['pid'] == $v['pid'] && isset($v['level'])) {
                        $level = $v['level'];
                        break;
                    }
                }
                $vo['level'] = $level;
                if ($level > 1) {
                    $repeatString = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
                    $markString = str_repeat("{$repeatString}├{$repeatString}", $level - 1);
                    $vo['title'] = $markString . $vo['title'];
                }
                $newList[] = $vo;
                $childList = $this->buildPidMenu($vo['id'], $list, $level);
                !empty($childList) && $newList = array_merge($newList, $childList);
            }

        }
        return $newList;
    }

    /**
     * @param int $pid
     * @param string $field
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getMallCateByPidList(int $pid = 0, string $field = '*'): array
    {
        return $this->field($field)
            ->where('pid', $pid)
            ->where('status', Status::mysql_normal)
            ->select()
            ->toArray();
    }
}